package com.jayqqaa12.service.system;

import com.jayqqaa12.jbase.jfinal.auto.BaseService;
import com.jayqqaa12.jbase.jfinal.ext.util.ListUtil;
import com.jayqqaa12.model.Tree;
import com.jayqqaa12.model.TreeKit;
import com.jayqqaa12.model.system.Res;
import com.jayqqaa12.model.system.Role;
import com.jayqqaa12.model.system.RoleRes;
import com.jayqqaa12.shiro.ShiroCache;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Generated by Jbase.
 */
public class RoleService extends BaseService<Role> {

    public boolean save(Role role, String res_ids) {

        boolean rst = false;
        if (role.getId() != null) rst = role.update();
        else rst = role.save();
        ShiroCache.clearAuthorizationInfoAll();

        ResService.me().batchGrant(role.getId(), res_ids);

        return rst;
    }




    @Override
    public List<Role> findAll() {
        List<Role> list = dao.find(sql("system_role.list"));

        list.forEach(r -> {
            List<Res> res = Res.dao.getRes(r.getId());
            r.put("res_ids", ListUtil.listToString(res, "id"));
            r.put("res_names", ListUtil.listToString(res, "name"));
        });

        return list;
    }

    /*
     根据用户角色来获取 列表
      */
    public List<Tree> getTree(Integer id, Integer passId) {

        return dao.getChild(id).stream()
                .filter(res -> !res.getId().equals(passId))
                .map(res -> {
                    Tree tree = new Tree(res.getId(), res.getPid(), res.getName(), res.getIconCls(), res, false);
                    tree.children = getTree(res.getId(), passId);
                    if (!tree.children.isEmpty()) tree.changeState();
                    return tree;
                })
                .collect(Collectors.toList());
    }




	public boolean delete(String id) {
		
		return TreeKit.deleteByIdAndPid(dao,id);
	}


}
